package com.gzhryc.shared_device.oem.code.member.services;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.IMemberCouponService;
import com.gzhryc.shared_device.base.enums.ECouponType;
import com.gzhryc.shared_device.base.models.IDeviceOrder;
import com.gzhryc.shared_device.base.models.IMemberCoupon;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.member.dao.MemberCouponDao;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberCoupon;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberCouponEnum;
import com.gzhryc.shared_device.oem.code.member.services.dto.MemberCouponSearch;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class MemberCouponService implements IMemberCouponService {

    static Logger log = Logger.getLogger(MemberCouponService.class);

    public static MemberCouponService self() {
        return MultiDBTools.getService(MemberCouponService.class, true);
    }

    public static MemberCouponService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, MemberCouponService.class, true);
    }

    MemberCouponDao dao;

    public MemberCouponService(String jdbcKey) {
        dao = new MemberCouponDao(jdbcKey);
    }

    public List<MemberCoupon> findBySearch(MemberCouponSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<MemberCoupon> findByMemberId(Long memberId){
        if(memberId != null){
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("memberId",memberId);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public MemberCoupon getNormalByActivityId(Long activityId){
        if(activityId != null){
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("activityId",activityId);
            conditions.and().is("state",MemberCouponEnum.State.Normal.index());

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    /**
     * 3个月优惠活动可以领取一次
     * @param activityId
     * @return
     */
    public MemberCoupon getByActivityId(Long activityId){
        if(activityId != null){
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("activityId",activityId);

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<MemberCoupon> findByUse(Long memberId,String businessType,Long placeId,Long money){
        if(memberId != null && placeId != null && StringTools.isNotBlank(businessType) && money != null){
            Integer minimumCharge = NumberTools.changeMoney(NumberTools.changeMoneyLi(money));
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("memberId",memberId);
            conditions.and().is("state",MemberCouponEnum.State.Normal.index());
            conditions.and().is("useLimit",CouponActivityEnum.UseLimit.Unlimited.index()).or().is("businessType",businessType);
            conditions.and().is("useRange",CouponActivityEnum.UseRange.Unlimited.index()).or().is("placeId",placeId);
            conditions.and().is("minimumCharge",0).or().le("minimumCharge",minimumCharge);
            conditions.asc("expirationDate");

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public Long countBySearch(MemberCouponSearch search){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.count(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public MemberCoupon getById(String id) {
        try {
            return dao.getById(id);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public boolean add(MemberCoupon memberCoupon) throws LogicException{
        if(memberCoupon.getMemberId() == null){
            throw new LogicException("请填写会员ID");
        }
        if(ECouponType.VOUCHERS.index().equals(memberCoupon.getCouponType())){
            if(memberCoupon.getCouponMoney() == null || memberCoupon.getCouponMoney() <= 0){
                throw new LogicException("请填写优惠金额");
            }
        }else if(ECouponType.DISCOUNT_COUPON.index().equals(memberCoupon.getCouponType())){
            if(memberCoupon.getCouponDiscount() == null || memberCoupon.getCouponDiscount() <= 0){
                throw new LogicException("请填写折扣信息");
            }
        }else if(ECouponType.COUPON_DAY.index().equals(memberCoupon.getCouponType())){
            if(memberCoupon.getCouponDay() == null || memberCoupon.getCouponDay() <= 0){
                throw new LogicException("请填写优惠天数");
            }
        }else {
            throw new LogicException("无效的优惠类型");
        }
        if(CouponActivityEnum.UseLimit.LimitBusinessType.index().equals(memberCoupon.getUseLimit())){
            if(StringTools.isBlank(memberCoupon.getBusinessType())){
                throw new LogicException("请填写业务类型");
            }
        }else {
            memberCoupon.setBusinessType(null);
        }

        Member member = MemberService.self().getById(memberCoupon.getMemberId());
        if (member == null) {
            throw new LogicException("未找到会员信息");
        }else {
            memberCoupon.setMemberName(member.getNickname());
        }
        if(memberCoupon.getPlaceId() != null){
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(memberCoupon.getPlaceId());
            if(physicalStore == null){
                throw new LogicException("未找到网点信息");
            }else{
                memberCoupon.setPlaceName(physicalStore.getName());
            }
        }
        memberCoupon.setCreateDate(new Date());
        try {
            return dao.insert(memberCoupon) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean toUsed(String id,String tradeNo,Date createDate){
        if(id != null && StringTools.isNotBlank(tradeNo) && createDate != null){
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("id",id);
            conditions.and().is("state", MemberCouponEnum.State.Normal.index());

            MemberCoupon updateEntity = new MemberCoupon();
            updateEntity.setState(MemberCouponEnum.State.Used.index());
            updateEntity.setUseTradeNo(tradeNo);
            updateEntity.setUseDate(createDate);

            try {
                return dao.updateNotNull(updateEntity,conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean toOverdue(String id){
        if(id != null){
            Conditions conditions = new Conditions(MemberCoupon.class);
            conditions.and().is("id",id);
            conditions.and().is("state", MemberCouponEnum.State.Normal.index());

            MemberCoupon updateEntity = new MemberCoupon();
            updateEntity.setState(MemberCouponEnum.State.Overdue.index());

            try {
                return dao.updateNotNull(updateEntity,conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteById(String id) throws LogicException {
        try {
            return dao.deleteById(id) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    @Override
    public IMemberCoupon getMemberCoupon(String businessType, IDeviceOrder deviceOrder) {
        List<MemberCoupon> memberCouponList = findByUse(deviceOrder.getMemberId(),businessType,deviceOrder.getPlaceId(),deviceOrder.getMoney());
        if(memberCouponList != null && memberCouponList.size() > 0){
            Date date = new Date();
            for(MemberCoupon memberCoupon : memberCouponList){
                if(date.after(memberCoupon.getExpirationDate())){
                    toOverdue(memberCoupon.getId());
                }else{
                    return memberCoupon;
                }
            }
        }
        return null;
    }
}
